// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({env: cloud.DYNAMIC_CURRENT_ENV});
const db = cloud.database();
const CustomError = require("./CustomError");

// 云函数入口函数
exports.main = async (event, context) => {
    return modules[event.actionName](event)
}

const modules = {
    /*
    * 添加留言
    * */
    addMessage: async function (event) {
        try {
            let {params} = event;
            let {OPENID} = cloud.getWXContext();
            await cloud.openapi.security.msgSecCheck({content: params.message});
            let res = await db.collection("message").add({
                data: Object.assign(params, {
                    verify: 0, //审核状态  /0审核中 1已通过 2未通过
                    openId: OPENID,
                    createTime: new Date().getTime()
                })
            })
            return {
                data: {_id: res._id},
                status: 0
            };
        } catch (e) {
            console.error("======" + event.actionName + "======");
            console.error(e)
            return new CustomError(e, event.actionName)
        }
    },

    /*
    * 删除留言
    * */
    deleteMessage: async function (event) {
        try {
            let {id} = event.params;
            if (!id) {throw new Error("参数为空")}
            let content = await db.collection("message").doc(id);
            let res = await content.get();
            if (res.data.images.length > 0) {
                await cloud.deleteFile({fileList: res.data.images})
            }
            await content.remove();
            return {
                data: content.data,
                status: 0,
            };
        } catch (e) {
            console.error("======" + event.actionName + "======");
            console.error(e)
            return new CustomError(e, event.actionName)
        }
    },

    /*
    * 获取留言列表
    * */
    getMessageList: async function (event) {
        try {
            const _ = db.command;
            const $ = db.command.aggregate;
            let {params} = event;
            let page = params.page - 1 || 0;
            let pageSize = params.pageSize || 20; //分页限制， 每页20
            let newData = {rid: params.rid}, verify;
            verify = (function (value) { //支持[x,x,x] 和 "x,x,x"格式的参数
                if (value || value === 0) {
                    return Array.isArray(value) ? (value.length > 0 ? value : false) : value.toString().split(",").map(function (item) {
                        return parseInt(item || 0)
                    })
                } else {
                    return false
                }
            })(params.verify)
            verify ? newData.verify = _.in(verify) : null;
            let aggregateInstance = await db.collection("message").aggregate()
                .match(newData)
                .sort({ //降序
                    createTime: -1
                })
                .skip(page * pageSize)
                .limit(pageSize)

            // let total = await aggregateInstance.count("total").end();
            let res = await aggregateInstance
                .lookup({
                    from: "user",
                    localField: "openId",
                    foreignField: "openId",
                    as: "userInfo"
                })
                .replaceRoot({
                    newRoot: $.mergeObjects([$.arrayElemAt(["$userInfo", 0]), "$$ROOT"])
                })
                .project({
                    city: 0,
                    country: 0,
                    userInfo: 0,
                    gender: 0,
                    language: 0,
                    province: 0
                })
                .end()
            return {
                data: {
                    list: res.list,
                    page: params.page,
                    pageSize: pageSize,
                    // total: total || 0,
                },
                status: 0
            }
        } catch (e) {
            console.error("======" + event.actionName + "======");
            console.error(e)
            return new CustomError(e, event.actionName)
        }
    }
}
